package com.lanou3g.zjl.chating.home.friends;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactListener;
import com.easemob.chat.EMContactManager;
import com.easemob.exceptions.EaseMobException;
import com.lanou3g.zjl.chating.R;
import com.lanou3g.zjl.chating.base.BaseFragment;
import com.lanou3g.zjl.chating.home.chatwindow.ChatWindowActivity;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.readystatesoftware.viewbadger.BadgeView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import butterknife.OnItemClick;
import butterknife.OnItemLongClick;


/**
 * Created by dllo on 15/11/17.
 */
public class FriendsFragment extends BaseFragment {
    //该集合存储好友
    private List<String> friendsNane;
    //适配器数据
    private List<FriendsInfo> data;
    //汉字转换成拼音的类
    private CharacterParser characterParser;
    //根据拼音来排列ListView里面的数据类
    private PinyinComparator pinyinComparator;
    //定义适配器
    private FriendsListAdapter adapter;
    //黑名单
    private List<String> blackList;
    //邀请者的集合
    private ArrayList<String> inviterList;
    //控件上的小红点,标记有多少条消息
    private BadgeView invitNum;

    private Handler handler;
    @Bind(R.id.dialog)
    TextView dialog;
    @Bind(R.id.sidrbar)
    SideBar sideBar;
    @Bind(R.id.country_lvcountry)
    ListView sortListView;

    @Bind(R.id.invitAndNotify)
    TextView showInviteNum;
    //跳转到添加好友界面
    @OnClick(R.id.addNewFriends)
    void addNewFriends() {
        Intent intent = new Intent(getActivity(), AddFriendsActivity.class);

        startActivity(intent);
    }

    //点击群聊跳转到群展示页面
    @OnClick(R.id.chatInGroup)
    void toGroup() {
        Intent intent = new Intent(getActivity(), GroupsActivity.class);
        startActivity(intent);
    }

    //点击跳转到申请与通知界面
    @OnClick(R.id.invitAndNotify)
    void toNotify() {
        if(invitNum.isShown()){
            invitNum.toggle();
        }
        Intent intent = new Intent(getActivity(), InvitInfoListActivity.class);
        intent.putStringArrayListExtra("list", inviterList);
        startActivity(intent);

    }

    @Override
    protected View getLayout(LayoutInflater inflater) {

        return inflater.inflate(R.layout.friendslist, null);
    }

    //@Override
    protected void initData() {
        invitNum = new BadgeView(getActivity(),showInviteNum);
        inviterList = new ArrayList<>();
        //接收异步执行消息
        getHandlerMessage();
        //获取黑名单
        getBlackList();
        // 实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        //初始化好友
        getFriendsName();

        //监听好友状态
        friendsMessageNotify();
    }

    //获得异步执行的消息
    private void getHandlerMessage() {

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                switch (message.what) {
                    case 1000:

                        invitNum.setText(inviterList.size() + "");
                        invitNum.setBadgeMargin(20, 20);
                        invitNum.setBadgeBackgroundColor(Color.BLUE);
                        invitNum.show();
                        break;
                    case 100:
                        //对方同意你的请求时刷新好友列表
                        // 根据a-z进行排序源数据
                        Collections.sort(data, pinyinComparator);
                        adapter.updateListView(data);
                        Toast.makeText(getActivity(), "同意了你的请求", Toast.LENGTH_SHORT).show();
                        break;
                    case 10:
                        initFriendsData();
                        break;
                }
                return false;
            }
        });
    }

    //获取黑名单
    private void getBlackList() {
        //获取黑名单
        final List<String> blackList = EMContactManager.getInstance().getBlackListUsernames();
        for (String s : blackList) {

            Log.i("lanou", "黑名单黑名单黑名单黑名单黑名单" + s);
        }
    }


    //获得该用户的好友
    private void getFriendsName() {
        //实例化数据
        data = new ArrayList<>();
        //初始化黑名单
        blackList = EMContactManager.getInstance().getBlackListUsernames();

        //EMChatManager.getInstance().getChatOptions().setUseRoster(true);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    friendsNane = EMContactManager.getInstance().getContactUserNames();//需异步执行
                    for (String s : friendsNane) {
                        //如果这些好友不在黑名单中则显示在好友列表中

                        if (!blackList.contains(s)) {

                            FriendsInfo info = new FriendsInfo();
                            info.setName(s);
                            // 汉字转换成全拼
                            String pinyin = characterParser.getSelling(s);
                            //字符串截取,获取拼音的首字母
                            //toUpperCase方法是讲字母转换成大写字母
                            String sortString = pinyin.substring(0, 1).toUpperCase();
                            // 正则表达式，判断首字母是否是英文字母
                            if (sortString.matches("[A-Z]")) {
                                //设置首字母
                                info.setSortLetter(sortString.toUpperCase());
                            } else {
                                info.setSortLetter("#");
                            }
                            //设置头像
                            info.setAvatar("jfdfjdkfl");
                            data.add(info);
                        }

                    }
                    Log.i("lanou", "---->>" + data.size());
                    handler.sendEmptyMessage(10);

                } catch (EaseMobException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }


    //将好友显示到好友列表中
    private void initFriendsData() {

        sideBar.setTextView(dialog);
        // 设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }

            }
        });
        // 根据a-z进行排序源数据
        Collections.sort(data, pinyinComparator);

        adapter = new FriendsListAdapter(getActivity(), data);
        sortListView.setAdapter(adapter);
    }

    //刷新好友列表
    private void refreshFrends() {
        adapter.updateListView(data);
    }

    //列表点击事件
    @OnItemClick(R.id.country_lvcountry)
    void OnItemClick(int position) {
        //点击好友跳转到聊天界面
        Intent intent = new Intent(getActivity(), ChatWindowActivity.class);
        intent.putExtra("username", (adapter.getItem(position)).getName());
        intent.putExtra("chattype", 1);
        Log.i("lanou", (adapter.getItem(position)).getName());
        startActivity(intent);
    }

    //删除好友/添加黑名单
    @OnItemLongClick(R.id.country_lvcountry)
    boolean longClick(final int position, View view) {

        PopupMenu popupMenu = new PopupMenu(getActivity(), view);
        popupMenu.getMenuInflater().inflate(R.menu.frendslist_menu, popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                switch (menuItem.getItemId()) {
                    case R.id.deletefrend:
                        //删除好友操作

                        try {
                            EMContactManager.getInstance().deleteContact((adapter.getItem(position)).getName());
                        } catch (EaseMobException e) {
                            e.printStackTrace();
                        }
                        data.remove(adapter.getItem(position));
                        //刷新好友列表
                        refreshFrends();
                        Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_LONG).show();

                        break;
                    //将好友添加到黑名单
                    case R.id.blacklist:
                        try {
                            EMContactManager.getInstance().addUserToBlackList((adapter.getItem(position)).getName(), true);
                            //刷新好友列表
                            data.remove(adapter.getItem(position));
                            refreshFrends();
                            Toast.makeText(getActivity(), "该好友已成功移到黑名单", Toast.LENGTH_LONG).show();
                        } catch (EaseMobException e) {
                            e.printStackTrace();
                        }
                        break;
                }
                return true;
            }
        });
        popupMenu.show();
        return false;
    }


    //监听好友状态事件
    private void friendsMessageNotify() {
        EMContactManager.getInstance().setContactListener(new MyContactListener());
        EMChat.getInstance().setAppInited();
    }

    private class MyContactListener implements EMContactListener {

        @Override
        public void onContactAdded(List<String> usernameList) {
            // 保存增加的联系人
//            for(String s : usernameList){
//                if(s.equals(EMChatManager.getInstance().getCurrentUser())){
//
//                }
            Log.i("lanou", usernameList.get(0) + ">>>>>>>>>>>>>>保存增加的联系人<<<<<<<<<<<" + EMChatManager.getInstance().getCurrentUser());
//            }
//            handler.sendEmptyMessage(1000);


        }

        @Override
        public void onContactDeleted(final List<String> usernameList) {
            // 被删除
            Log.i("lanou", usernameList.get(0) + ">>>>>>>>>>>>>>被删除<<<<<<<<<<<");
        }

        @Override
        public void onContactInvited(final String username, String reason) {
            // 接到邀请的消息，如果不处理(同意或拒绝)，掉线后，服务器会自动再发过来，所以客户端不要重复提醒
            if (!inviterList.contains(username)) {
                inviterList.add(username);
            }
            handler.sendEmptyMessage(1000);
            Log.i("lanou", ">>>>>>>>>>>>>>接到" + username + "邀请的消息<<<<<<<<<<<" + reason);

        }

        @Override
        public void onContactAgreed(final String username) {

            FriendsInfo info = new FriendsInfo();
            info.setName(username);
            // 汉字转换成全拼
            String pinyin = characterParser.getSelling(username);
            //字符串截取,获取拼音的首字母
            //toUpperCase方法是讲字母转换成大写字母
            String sortString = pinyin.substring(0, 1).toUpperCase();
            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                //设置首字母
                info.setSortLetter(sortString.toUpperCase());
            } else {
                info.setSortLetter("#");
            }
            //设置头像
            info.setAvatar("jfdfjdkfl");

            if (!data.contains(info))
                data.add(info);

            Log.i("lanou", username + ">>>>>>>>>>>>>>同意好友请求<<<<<<<<<<<" + EMChatManager.getInstance().getCurrentUser());
            handler.sendEmptyMessage(100);
        }

        @Override
        public void onContactRefused(String username) {
            // 拒绝好友请求
            Log.i("lanou", username + ">>>>>>>>>>>>>>拒绝好友请求<<<<<<<<<<<");
        }

    }

}
